package com.aaron.kjviewutils.stock;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aaron.kjviewutils.BaseActivity;
import com.aaron.kjviewutils.DropDownMenuAdapter;
import com.aaron.kjviewutils.R;
import com.aaron.kjviewutils.eventBus.BundleEventMsg;
import com.aaron.kjviewutils.eventBus.EventBusMsg;
import com.aaron.kjviewutils.flight.FlightAdapter;
import com.aaron.kjviewutils.footballleague.TabPagerStateAdapter;
import com.aaron.kjviewutils.retrofit.RetrofitUtil;
import com.aaron.kjviewutils.spinkit.PoponDismissListener;
import com.github.ybq.android.spinkit.Style;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.yyydjk.library.DropDownMenu;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import q.rorbin.verticaltablayout.VerticalTabLayout;
import q.rorbin.verticaltablayout.widget.TabView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Aaron on 2017/3/1.
 */

public class StockActivity extends BaseActivity {

    @Bind(R.id.stockToolBar)
    Toolbar stockToolBar;
    @Bind(R.id.barTitle)
    TextView barTitle;
    @Bind(R.id.leftBarIcon)
    ImageView leftBarIcon;
    @Bind(R.id.stockDropDownMenu)
    DropDownMenu stockDropDownMenu;
    @Bind(R.id.stockTabs)
    VerticalTabLayout stockTabs;
    @Bind(R.id.stockViewpager)
    ViewPager stockViewpager;

    private StockService stockService;
    private Call<ResponseBody> callStocks;
    private Call<StockBean> callStockDetail;
    private List<String> tips;
    private Map<String, String> subDatas;
    private TabPagerStateAdapter adapter;
    private List<Fragment> fragments;
    private List<String> vTabs;
    private MsgPopWin msgPopWin;

    @OnClick(R.id.leftBarIcon)
    void leftBarIconClick()
    {
        if (stockDropDownMenu.isShowing()) {
            stockDropDownMenu.closeMenu();
        }
        else
        {
            //关闭
            closeSelf(StockActivity.this);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, priority = 80)
    public void onEvent(EventBusMsg msg)
    {
        switch (msg.getType())
        {
            case STOCK_MEU_UI:
            {
                //加载menu
                final List<String> carteTags = new ArrayList<String>();
                carteTags.add("选择区域");
                final List<View> popupViews = new ArrayList<View>();
                int size = carteTags.size();
                for(int i=0; i<size; i++)
                {
                    final int index = i;
                    final DropDownMenuAdapter dapter = new DropDownMenuAdapter(StockActivity.this, tips);
                    RecyclerView recyclerView = new RecyclerView(this);
                    recyclerView.setLayoutManager(new LinearLayoutManager(StockActivity.this));
                    recyclerView.setItemAnimator(new DefaultItemAnimator()); // 默认动画
                    recyclerView.setLayoutParams(new RecyclerView.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT/3, RecyclerView.LayoutParams.MATCH_PARENT));
                    recyclerView.setAdapter(dapter);
                    dapter.setmOnItemClickListener(new FlightAdapter.OnItemClickListener() {
                        @Override
                        public void onItemClick(View view, int position) {
                            stockDropDownMenu.setTag(tips.get(position));
                            if(-1==position)
                            {
                                stockDropDownMenu.setTabText(carteTags.get(position));
                            }
                            else
                            {
                                switch (tips.get(position))
                                {
                                    case "africa":
                                    {
                                        stockDropDownMenu.setTabText("非洲");
                                    }
                                    break;
                                    case "oceania":
                                    {
                                        stockDropDownMenu.setTabText("大洋洲");
                                    }
                                    break;
                                    case "euro":
                                    {
                                        stockDropDownMenu.setTabText("欧洲");
                                    }
                                    break;
                                    case "america":
                                    {
                                        stockDropDownMenu.setTabText("美洲");
                                    }
                                    break;
                                    case "asia":
                                    {
                                        stockDropDownMenu.setTabText("亚洲");
                                    }
                                    break;
                                    default:
                                        break;
                                }
                            }
                            stockDropDownMenu.closeMenu();
                            Bundle bundle = new Bundle();
                            bundle.putString("tab", String.valueOf(stockDropDownMenu.getTag()));
                            eventBus.post(new BundleEventMsg(BundleEventMsg.EventBusType.STOCK_SUBMEU_UI, bundle));
                        }
                    });
                    popupViews.add(recyclerView);
                }
                LinearLayout contentView = new LinearLayout(this);
                contentView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT/3, LinearLayout.LayoutParams.MATCH_PARENT));
                stockDropDownMenu.setDropDownMenu(carteTags, popupViews, contentView);
            }
            break;
            default:
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, priority = 80)
    public void onEvent(final BundleEventMsg msg)
    {
        switch (msg.getType())
        {
            case STOCK_SUBMEU_UI:
            {
                Bundle bundle=msg.getBundle();
                String tab = bundle.getString("tab");
                //加载侧边栏
                if(null!=subDatas&&subDatas.containsKey(tab))
                {
                    String source = subDatas.get(tab);
                    //解析
                    JsonParser parser = new JsonParser();
                    JsonObject json01 = parser.parse(source).getAsJsonObject();
                    fragments = new ArrayList<Fragment>();
                    if(null!=json01&&json01.size()>0)
                    {
                        vTabs = new ArrayList<String>();
                        Iterator iterator = json01.entrySet().iterator();
                        while (iterator.hasNext())
                        {
                            Map.Entry<String, JsonElement> jsonEntry = (Map.Entry<String, JsonElement>) iterator.next();
                            StockFragment stockFragment = new StockFragment();
                            Bundle bundle1 = new Bundle();
                            bundle1.putString("stock", jsonEntry.getValue().toString());
                            bundle1.putString("continentType", tab);
                            bundle1.putString("countryName", jsonEntry.getKey());
                            stockFragment.setArguments(bundle1);
                            fragments.add(stockFragment);
                            vTabs.add(jsonEntry.getKey());
                        }
                        adapter = new TabPagerStateAdapter(getSupportFragmentManager(), fragments);
                        stockViewpager.setAdapter(adapter);
                        stockTabs.setupWithViewPager(stockViewpager);
                        stockTabs.setTabMode(VerticalTabLayout.TAB_MODE_SCROLLABLE);
                        if(null!=vTabs&&!vTabs.isEmpty())
                        {
                            int size = vTabs.size();
                            for(int i=0; i<size; i++)
                            {
                                //初始化tabs
                                TabView tabView = stockTabs.getTabAt(i);
                                tabView.setTitle(new TabView.TabTitle.Builder().setContent(vTabs.get(i)).setTextColor(0xFFFFFFFF, 0xFFD6DBE1).setTextSize(px2dp(StockActivity.this.getResources().getDimension(R.dimen.pickerview_title))).build());
                            }
                        }
                    }
                }
            }
            break;
            case STOCK_SUBMEU_UI_DETAIL:
            {
                Bundle bundle = msg.getBundle();
                String continentType = bundle.getString("continentType");
                String countryName = bundle.getString("countryName");
                String code = bundle.getString("code");
                Map<String, String> map = new HashMap<String, String>();
                map.put("continentType", continentType);
                map.put("countryName", countryName);
                map.put("code", code);
                if(null!=progress)
                {
                    progress.showProgress(Style.WAVE);
                    progress.showAtLocation(stockToolBar, Gravity.CENTER, 0, 0);
                }
                //获取航班信息
                if(null==retrofit)
                {
                    retrofit = RetrofitUtil.obtainRetrofit();
                }
                stockService = retrofit.create(StockService.class);
                callStockDetail = stockService.obtainStockDetail(map);
                callStockDetail.enqueue(new Callback<StockBean>() {
                    @Override
                    public void onResponse(Call<StockBean> call, Response<StockBean> response) {
                        callStockDetail.cancel();
                        if (null != progress) {
                            progress.dismissView();
                        }
                        StockBean stockDetail = response.body();
                        if("200".equals(stockDetail.retCode))
                        {
                            if(null!=stockDetail)
                            {
                                msgPopWin = new MsgPopWin(StockActivity.this, StockActivity.this);
                                msgPopWin.showUi(stockDetail.result, MsgPopWin.MsgType.MSG_STOCK);
                                msgPopWin.showAtLocation(stockToolBar, Gravity.CENTER, 0, 0);
                                msgPopWin.setOnDismissListener(new PoponDismissListener( StockActivity.this ));
                            }
                            else
                            {
                                showMsg("获取数据失败");
                            }
                        }
                        else
                        {
                            showMsg(stockDetail.msg);
                        }
                    }

                    @Override
                    public void onFailure(Call<StockBean> call, Throwable t) {
                        callStockDetail.cancel();
                        if (null != progress) {
                            progress.dismissView();
                        }
                        showMsg("获取数据失败");
                    }
                });
            }
            break;
            default:
                break;
        }
    }

    Runnable runnableLoadData = new Runnable() {
        @Override
        public void run() {
            if(null!=progress)
            {
                progress.showProgress(Style.WAVE);
                progress.showAtLocation(stockToolBar, Gravity.CENTER, 0, 0);
            }
            //获取航班信息
            if(null==retrofit)
            {
                retrofit = RetrofitUtil.obtainRetrofit();
            }
            stockService = retrofit.create(StockService.class);
            callStocks = stockService.obtainGlobalStock();
            callStocks.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    callStocks.cancel();
                    if (null != progress) {
                        progress.dismissView();
                    }
                    try
                    {
                        String source = response.body().string();
                        if(TextUtils.isEmpty(source))
                        {
                            showMsg("获取数据失败");
                        }
                        else
                        {
                            Gson gson = new Gson();
                            JSONObject resultJson = new JSONObject(source);
                            if("200".equals(resultJson.getString("retCode")))
                            {
                                tips = new ArrayList<String>();
                                subDatas = new HashMap<String, String>();
                                JsonParser parser = new JsonParser();
                                JsonObject json01 = parser.parse(source).getAsJsonObject();
                                JsonObject json02 = json01.getAsJsonObject("result");
                                Iterator iterator = json02.entrySet().iterator();
                                while (iterator.hasNext())
                                {
                                    Map.Entry<String, JsonElement> jsonEntry = (Map.Entry<String, JsonElement>) iterator.next();
                                    tips.add(jsonEntry.getKey());
                                    subDatas.put(jsonEntry.getKey(), jsonEntry.getValue().toString());
                                }
                                eventBus.post(new EventBusMsg(EventBusMsg.EventBusType.STOCK_MEU_UI));
                            }
                            else
                            {
                                showMsg(resultJson.getString("msg"));
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        showMsg("获取数据失败");
                    }
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                    callStocks.cancel();
                    if (null != progress) {
                        progress.dismissView();
                    }
                    showMsg("获取数据失败");
                }
            });
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.layout_stock);
        ButterKnife.bind(this);
        initTitle();
        initContent();
    }

    private void initTitle()
    {
        stockToolBar.setTitle("");
        barTitle.setText("全球股指查询");
        loadBackground(leftBarIcon, resources.getDrawable(R.mipmap.back));
        stockToolBar.setNavigationIcon(null);
    }

    private void initContent()
    {
        mHandler.postDelayed(runnableLoadData, 1000);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN)
        {
            if (stockDropDownMenu.isShowing()) {
                stockDropDownMenu.closeMenu();
                return true;
            }
            else
            {
                //关闭
                closeSelf(StockActivity.this);
                return super.onKeyDown(keyCode, event);
            }
        }
        return true;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(null!=mHandler)
        {
            mHandler.removeCallbacks(runnableLoadData);
        }
        if(null!=progress)
        {
            progress.dismissView();
        }
        if(null!=msgPopWin)
        {
            msgPopWin.dismissView();
        }
        if(null!=callStocks)
        {
            callStocks.cancel();
        }
        if(null!=callStockDetail)
        {
            callStockDetail.cancel();
        }
        ButterKnife.unbind(this);
    }
}
